import Databus from '../databus'
const databus = new Databus()

export default class Pipe {
    constructor(){
        this.image1 = databus.imgObj.pipe_down
        this.image2 = databus.imgObj.pipe_up
        // 位置
        this.x = databus.canvas.width
        this.y1 = 0
        // 宽高
        this.w = this.image1.width
        this.h1 = Math.floor(Math.random() * (300 - 200 + 1)) + 200
        this.door = Math.floor(Math.random() * (130 - 100 + 1)) + 100
        this.y2 = this.h1 + this.door
        this.h2 = databus.canvas.height - this.y2 - databus.imgObj.land.height
        this.sy1 = this.image1.height - this.h1
        databus.addActor(this)
        this.noPass = true
    }
    update(){
        this.x -= databus.speed
        // 删除点
        if (this.x <= -this.w){
            this.die()
            // console.log(databus.actors.length)
        }
        // 更新检测盒
        // 小鸟的碰撞范围
        const lx = databus.bird.x + 6
        const rx = databus.bird.x + 40
        const ty = databus.bird.y + 10
        const by = databus.bird.y + 40
        // 管子的碰撞范围
        this.lx1 = this.x
        this.rx1 = this.x + this.w
        this.ty1 = this.h1
        this.by2 = this.y2
        // 碰撞检测
        if(rx >= this.lx1 && lx <= this.rx1 && (ty <= this.ty1 || by >= this.by2)){
            databus.scene = 2
        }
        // 小鸟经过管子添加一分
         if( rx >= this.x && this.noPass  ){
            databus.score ++
            this.noPass = false
         }
    }
    render(){
        databus.ctx.drawImage(this.image1, 0, this.sy1, this.w, this.h1, this.x, this.y1, this.w, this.h1)
        databus.ctx.drawImage(this.image2, 0, 0, this.w, this.h2, this.x, this.y2, this.w, this.h2)
    }
    die(){
        databus.actors = databus.actors.filter(item => {
            return item !== this
        })
    }
}